package net.jxtz.jxtzos.spider;

import lombok.extern.slf4j.Slf4j;
import net.jxtz.jxtzos.entity.spider.SpiderLogServe;
import org.springframework.context.ApplicationContextAware;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lmh
 * @version 1.0
 * @date 2021-09-10 10:01
 */

@Slf4j
public class SpiderFactory {

    private final static Map<String, BaseSpiderProcessor> SPIDER_PROCESSOR = new ConcurrentHashMap<>(8);

    private final static Map<String, SpiderDefinition> SPIDER_DEFINITION = new ConcurrentHashMap<>(8);

    private final static SpiderFactory SPIDER = new SpiderFactory();

    public static SpiderFactory getInstance() {
        return SPIDER;
    }

    private SpiderFactory(){}

    public void putSpiderDefinition(String key, SpiderDefinition spiderDefinition) {
        SPIDER_DEFINITION.put(key, spiderDefinition);
    }

    public void putSpiderProcess(String key, BaseSpiderProcessor spiderProcessor) {
        log.info("放入 --> " + key + " --> " + spiderProcessor.getClass().getName());
        SPIDER_PROCESSOR.put(key, spiderProcessor);
    }

    public void invokeSpiderStart(String key, SpiderLogServe spiderLogServe, SpiderDefinition spiderDefinition) {
        try {
            SPIDER_PROCESSOR.get(key).start(spiderLogServe, spiderDefinition);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void invokeSpiderStart(String key) {
        SpiderLogServe spiderLogServe = new SpiderLogServe();
        final long l = System.currentTimeMillis();
        System.out.println("spiderLogId: " + l);
        spiderLogServe.setId(l);
        try {
            SPIDER_PROCESSOR.get(key).start(spiderLogServe, null);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }


    public List<SpiderDefinition> getSpiderKey() {
        return new ArrayList<>(SPIDER_DEFINITION.values());
    }

}
